package com.m1.android.data.dao;

import java.util.ArrayList;
import java.util.List;

import com.m1.android.data.db.SmsShieldWordColumns;
import com.m1.android.data.db.util.SqliteWrapper;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;

public class SmsShieldWordDao {
	private static final List<String> CACHE = new ArrayList<String>();

	public static void clearSmsShieldWord(Context context) {
		CACHE.clear();
		SqliteWrapper.delete(context, context.getContentResolver(), SmsShieldWordColumns.CONTENT_URI, null, null);
	}

	public static void addSmsShieldWord(Context context, String keyword) {
		checkCache(context);
		if (!CACHE.contains(keyword)) {
			CACHE.add(keyword);
			ContentValues values = new ContentValues();
			values.put(SmsShieldWordColumns.COLUMN_WORD, keyword);
			SqliteWrapper.insert(context, context.getContentResolver(), SmsShieldWordColumns.CONTENT_URI, values);
		}
	}

	public static boolean constainsShieldWord(Context context, String str) {
		checkCache(context);
		boolean constains = false;
		if (!TextUtils.isEmpty(str)) {
			for (String keyword : CACHE) {
				if (str.contains(keyword)) {
					constains = true;
					break;
				}
			}
		}
		return constains;
	}

	public static int getSmsShieldWordCount(Context context) {
		Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(), SmsShieldWordColumns.CONTENT_URI,
				new String[] { SmsShieldWordColumns.COLUMN_WORD }, null, null, null);
		int count = 0;
		if (cursor != null) {
			count = cursor.getCount();
			cursor.close();
		}
		return count;
	}

	private static void checkCache(Context context) {
		if (CACHE.isEmpty()) {
			initCache(context);
		}
	}

	private static void initCache(Context context) {
		Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(), SmsShieldWordColumns.CONTENT_URI,
				new String[] { SmsShieldWordColumns.COLUMN_WORD }, null, null, null);
		if (cursor != null) {
			while (cursor.moveToNext()) {
				String word = cursor.getString(cursor.getColumnIndex(SmsShieldWordColumns.COLUMN_WORD));
				if (!CACHE.contains(word)) {
					CACHE.add(word);
				}
			}
			cursor.close();
		}
	}
}
